/**
 * Created by chaos on 2017/7/4.
 */
import Vue from 'vue'
import WechatPlugin from 'vux/src/plugins/wechat/index.js'
import LoadingPlugin from 'vux/src/plugins/loading/index.js'
import VueResource from 'vue-resource'
Vue.use(WechatPlugin)
Vue.use(LoadingPlugin)
Vue.use(VueResource)
const plugin = {
  install: function (vue, options) {
    vue.$chaos = {
      common_config: {
        debug: true,
        importIndex: 0,
        wxLogin: true,
        mode: 'website',
        baseUrl: 'api.php',
        authType: 'weixin', //  weixin 仅支持微信登录  mixd 自建鉴权和微信混用  user 自建鉴权
        customLoginAuth: function () { // 仅首次验证登录信息时调用
          return true
        },
        customAuth: function () { // 每次鉴权均会调用
          return true
        },
        verifyFail: function () { // 鉴权失败会调用

        },
        loginUrl: '/#/Login/login',
        callbackUrl: '',
        wxConfig: {
          scope: 'snsapi_base',
          appid: '',
          agentid: ''
        }
      },
      config: function (key, value) {
        if (typeof key === 'object') {
          this.common_config = Object.assign(this.common_config, key)
        } else if (typeof key === 'string' && typeof value !== 'undefined') {
          this.common_config[key] = value
        } else if (typeof key === 'string') {
          return this.common_config[key]
        }
      },
      setTitle: function (title) {
        document.title = title
        if (this.isWechat()) {
          var i = document.createElement('iframe')
          i.src = '//m.baidu.com/favicon.ico'
          i.style.display = 'none'
          i.onload = function () {
            setTimeout(function () {
              i.remove()
            }, 9)
          }
          document.body.appendChild(i)
        }
      },
      isWechat: function () {
        var ua = navigator.userAgent.toLowerCase()
        if (/micromessenger/i.test(ua)) {
          return true
        } else {
          return false
        }
      },
      importJssdk: function () {
        vue.wechat.config({
          debug: true, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
          appId: '', // 必填，公众号的唯一标识
          timestamp: 1213121212, // 必填，生成签名的时间戳
          nonceStr: '', // 必填，生成签名的随机串
          signature: '', // 必填，签名，见附录1
          jsApiList: [] // 必填，需要使用的JS接口列表，所有JS接口列表见附录2
        })
      },
      getUserInfo: function () {
        let mode = this.config('mode')
        if (mode === 'website' && sessionStorage.userinfo) {
          return JSON.parse(sessionStorage.userinfo)
        } else if (mode === 'client' && localStorage.userinfo) {
          let userinfo = JSON.parse(localStorage.userinfo)
          if (userinfo.expire_time * 1000 < new Date().getTime()) {
            localStorage.userinfo = null
            return false
          }
          return userinfo
        } else {
          return false
        }
      },
      setUserInfo: function (userinfo) {
        let mode = this.config('mode')
        if (mode === 'website') {
          sessionStorage.userinfo = JSON.stringify(userinfo)
        } else {
          localStorage.userinfo = JSON.stringify(userinfo)
        }
      },
      setAccessToken: function (accessToken, expireIn) {
        let mode = this.config('mode')
        let storage = JSON.stringify({
          accessToken: accessToken,
          // expireIn: expireIn * 1000 + new Date().getTime()
          expireIn: new Date().getTime() + 30 * 86400000
        })
        if (mode === 'website') {
          sessionStorage.accessToken = storage
        } else {
          localStorage.accessToken = storage
        }
      },
      getAccessToken: function () {
        let mode = this.config('mode')
        let storage = ''
        if (mode === 'website') {
          storage = sessionStorage.accessToken
        } else {
          storage = localStorage.accessToken
        }
        if (storage !== null && storage !== undefined) {
          let accessToken = JSON.parse(storage)
          if (accessToken) {
            if (accessToken.expireIn > new Date().getTime()) {
              return accessToken.accessToken
            }
          }
        }
        this.clearAccessToken()
        return false
      },
      clearAccessToken: function () {
        localStorage.accessToken = null
        sessionStorage.accessToken = null
      },
      verify: function (callback, param) {
        let accessToken = this.getAccessToken()
        if (accessToken) {
          let userinfo = this.getUserInfo()
          let authResult = this.common_config.customAuth(param)
          if (!authResult) {
            if (callback.error) {
              callback.error({info: 'customAuthFail'})
            } else {
              this.common_config.verifyFail({info: 'customAuthFail'})
            }
            return false
          } else {
            if (typeof callback === 'function') {
              callback(userinfo)
            } else {
              callback.success(userinfo)
            }
          }
        } else {
          this.setBackUrl(location.href)
          location.href = this.config('loginUrl')
        }
      },
      ajax: function (opt) {
        if (!opt.callback || !opt.url) {
          return false
        }
        if (!opt.type) opt.type = 'post'
        if (!opt.data) opt.data = {}
        if (!opt.timeout) opt.timeout = 5000
        if (opt.slient === undefined) {
          if (opt.loading) {
            vue.$vux.loading.show({
              text: opt.loading
            })
          } else {
            vue.$vux.loading.show({
              text: '加载中'
            })
          }
        } else if (!opt.slient) {
          vue.$vux.loading.show({
            text: '加载中'
          })
        }
        opt.headers = {
          'X-Requested-With': 'XMLHttpRequest',
          'accept': 'application/json'
        }
        if (opt.userinfo) {
          opt.data.access_token = this.getAccessToken()
        }
        if (opt.file) {
          opt.headers['Content-Type'] = 'multipart/form-data'
          if (opt.userinfo) {
            opt.data.append('access_token', this.getAccessToken())
          }
          // opt.data['Content-Type'] = 'multipart/form-data'
        }
        let url = this.formatUrl(opt.url)
        vue.http({
          url: url,
          body: opt.data,
          timeout: opt.timeout,
          method: opt.type,
          headers: opt.headers,
          emulateJSON: !opt.file
        }).then(function (ret) {
          if (!opt.slient) {
            vue.$vux.loading.hide()
          }
          if (ret.body.status === 'SUCCESS') {
            opt.callback('success', ret.body)
          } else {
            if (ret.body.status === 'ERROR') {
              let errMsg = '网络错误，请重试'
              if (ret.body.result === '') {

              } else if (typeof ret.body.result === 'string') {
                errMsg = ret.body.result
              } else if (typeof ret.body.result === 'object') {
                for (let i in ret.body.result) {
                  if (typeof ret.body.result[i] === 'object') {
                    errMsg = ret.body.result[i][0]
                  } else {
                    errMsg = ret.body.result[i]
                  }
                }
              }
              vue.$vux.toast.show({
                text: errMsg,
                width: '160px',
                position: 'middle',
                type: 'text'
              })
            }
            opt.callback(ret.body.status === 'ERROR' ? 'fail' : 'error', ret.body)
          }
        }, function (ret) {
          if (!opt.slient) {
            vue.$vux.loading.hide()
            if (ret.body.status !== 'ERROR') {
              vue.$vux.toast.show({
                text: '网络发生故障,请重试',
                width: '160px',
                position: 'middle',
                type: 'text'
              })
            }
          }
          opt.callback(ret.body.status === 'ERROR' ? 'fail' : 'error', ret.body)
        })
      },
      getQueryString: function (name) {
        var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i')
        var r = location.href.substr(location.href.indexOf('?') + 1).match(reg)  // 获取url中"?"符后的字符串并正则匹配
        var context = ''
        if (r !== null) {
          context = r[2]
        }
        reg = null
        r = null
        return context === null || context === '' || context === 'undefined' ? '' : context
      },
      formatUrl: function (url) {
        return this.config('baseUrl') + '/' + url
      },
      setBackUrl: function (url) {
        sessionStorage.backurl = url
      },
      getBackUrl: function () {
        return sessionStorage.backurl ? sessionStorage.backurl : this.config('indexUrl')
      },
      goBack: function () {
        location.href = this.getBackUrl()
      }

    }
    vue.mixin({
      created: function () {
        this.$chaos = vue.$chaos
      }
    })
  }
}
export default plugin
export const install = plugin.install
